package com.jiuqi.lr_demo.service.impl;

import com.jiuqi.lr_demo.dao.UserDao;
import com.jiuqi.lr_demo.entity.User;
import com.jiuqi.lr_demo.exception.ServiceException;
import com.jiuqi.lr_demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public List<User> getAllUsers() {
        return userDao.getAllUsers();
    }

    @Override
    public User getUserById(int id) {
        User user = userDao.getUserById(id);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        return user;
    }

    @Override
    public User getUser(User user) {

        //根据username查询用户信息
        User dbUser = userDao.getUserByUsername(user.getUsername());
        if (dbUser == null) {
            //throw new Exception("用户不存在");
            throw new ServiceException(user.getUsername() + " 用户不存在");
        }
        if (!dbUser.getPassword().equals(user.getPassword())) {
            throw new ServiceException(user.getPassword() + " 用户密码错误");
        }
        return dbUser;
    }

    @Override
    public boolean addUser(User user) {
        boolean flag = userDao.addUser(user);
        return flag;
    }

    @Override
    public boolean updateUser(User user) {
        return userDao.updateUser(user);
    }

    @Override
    public boolean deleteUser(int id) {
        if (userDao.getUserById(id) == null) {
            throw new ServiceException("用户不存在");
        }
        return userDao.deleteUser(id);
    }
}
